import java.util.Arrays;

public class Myarraylist2 implements IList {
    public int[] elem;
    public final static int DEFAULT_SIZE = 10;
    public int usesize = 0;

    public Myarraylist2() {
        this.elem = new int[DEFAULT_SIZE];
    }

    public Myarraylist2(int capacity) {
        this.elem = new int[capacity];
    }

    @Override
    public void add(int data) {
       checkCapacity();
        elem[usesize] = data;
        usesize++;
    }


    @Override
    public void add(int pos, int data) {
        try {
            checkPos(pos);
        } catch (PosNotlegally e) {
e.printStackTrace();
        }
checkCapacity();
        for (int i = usesize-1; i >=pos; i--) {
            elem[i+1] = elem[i];
        }
        elem[pos] = data;
        usesize++;
    }

    @Override
    public boolean contains(int toFind) {
        if(isEmpty()){
            return false;
        }
        for (int i = 0; i <usesize ; i++) {
            if(elem[i]==toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        if (isEmpty()) {
            return -1;
        }
        for (int i = 0; i < usesize; i++) {
            if (elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        if(isEmpty()){
            return -1;
        }
        checkPos(pos);
        return elem[pos];
    }

    @Override
    public void set(int pos, int value) {
checkPos(pos);
elem[pos] = value;
    }

    @Override
    public void remove(int toRemove) {
if (isEmpty()){
    System.out.println("数组为空");
    return;
}
int flag = 0;
        for (int i = 0; i <usesize-1; i++) {
            if (elem[i]==toRemove){
              flag=1;
            }
            if(flag==1){
                elem[i] = elem[i+1];
            }
        }
        usesize--;
    }

    @Override
    public int size() {
       return usesize;
    }

    @Override
    public void clear() {
        usesize = 0;

    }

    @Override
    public void display() {
        for (int i = 0; i < usesize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }

    @Override
    public boolean isFull() {
        if (usesize == elem.length) {
            return true;
        }
        return false;
    }
private void checkCapacity(){
    if (isFull()){
        elem = Arrays.copyOf(elem, elem.length * 2);
    }

}
private void checkPos(int pos) throws PosNotlegally{
    if(pos<0 || pos>usesize){
       throw new RuntimeException("插入元素下标异常"+pos);
    }
}
private boolean isEmpty(){
      return usesize==0;
    }
}

